﻿using System;
using System.Data.Linq;
using System.Linq;
using CoreLibrary.Repo;
using Entities.DataBase.Persistent;
using Entities.DataBase.Sql;

namespace Entities.DataBase.Impl {

    public class IntGuidRepository : BaseRepository<IntGuid>, IIntGuidRepository{
        
        private const string IntGuidID = "INT_GUID_ID";

        public override string TableName {
            get {
                return "D_INT_GUID";
            }
        }

        private static readonly Func<DataContext,IntGuid>
            LinqGetIntGuid = CompiledQuery.Compile((DataContext context)
                => context.GetTable<IntGuid>().SingleOrDefault(o => o.Id.Equals(IntGuidID)));
        
        protected override void OnStart() {
            base.OnStart();
            Execute((context, ts) => {
                var guid = LinqGetIntGuid(context);
                if (guid == null) {
                    context.GetTable<IntGuid>().InsertOnSubmit(new IntGuid {
                        Id   = IntGuidID,
                        Guid = 10000
                    });
                }
                context.SubmitChanges();
                ts.Complete();
            });
        }

        public int GenerateGuid() {
            return Execute(new UpdateOutputIntGuid(TableName, 1));
        }
        
    }
}